package net.ib.mtalk.network.task;

import java.util.List;
import java.util.UUID;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mntalk.protocol.Session.RemoveViewReq;
import net.ib.mntalk.protocol.Session.RemoveViewRes;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

/**
 * 서버에 뷰 삭제를 요청한다.
 * 
 * @author happy2v
 *
 */
public class RemoveViewTask extends AsyncNetTask {
	
	private RemoveViewReq mRemoveViewReq;
	private List<UUID> mClientUuid;
	private List<UUIDMsg> mViewUuid;
	
	/**
	 * 
	 * @param context
	 * @param handler
	 * @param removeViewReq
	 * @param clientUuidList
	 * @param viewUuidList
	 */
	public RemoveViewTask(Context context, Handler handler, List<UUID> clientUuidList, List<UUIDMsg> viewUuidList){
		super(context, handler);
		this.mRemoveViewReq = new RemoveViewReq();
		this.mClientUuid = clientUuidList;
		this.mViewUuid = viewUuidList;
	}
	
	@Override
	protected TcpEnvelope onPreExecute() {
		
		// 클라이언트 UUID로 설정되었을때.
		if(mClientUuid != null){
			for(int i = 0; i < mClientUuid.size(); i++){
				mRemoveViewReq.addViewUuid(InboxDatabaseHelper.getViewUUID(mContext, mClientUuid.get(i)));
			}
		}else if(mViewUuid != null){ // View UUID로 설정되었을때.
			for(int i = 0; i < mViewUuid.size(); i++){
				mRemoveViewReq.addViewUuid(mViewUuid.get(i));
			}
		}else{ // clientUuid 및 viewUuid 가 설정되어 있지 않으면 전부 
			
			
		}
		
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(mRemoveViewReq)
			.setMethodId(Session.View.RemoveView)
			.build();
		return rev;
	}
	
	@Override
	protected void onPostExecute(int resultCode, Object sentObject,
			Object receivedObject) {
		MTalkLogWriter.d("RemoveViewTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		RemoveViewRes removeViewRes = (RemoveViewRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("RemoveViewTask ResponseCode : " + removeViewRes.getResponseCode());
		
		if(removeViewRes.getResponseCode() == Common.SUCCESS){
			/*// 성공적으로 메시지가 지워졌다!!
			// 확실하게 지워졌는지 확인하자!!
//			// TODO : 이걸로 써야됨
			
			// 요청한 뷰와 성공한 뷰를 비교해서 지워지지 않은 것은 다시 요청하자.
			// 요청과 성공 갯수가 같지 않으면 확인이 필요한 것이다.
			if(mRemoveViewReq.getViewUuidCount() != removeViewRes.getRemoveSuccessUuidCount()){
				for(int i = 0; i < mRemoveViewReq.getViewUuidCount(); i++){
					mRemoveViewReq.getViewUuidList();
					if((removeViewRes.getRemoveSuccessUuidList().contains(mRemoveViewReq.getViewUuid(i)))){
						InboxDatabaseHelper.deleteView(mContext, mRemoveViewReq.getViewUuid(i)); //DB 작업
					}
//					if((removeViewRes.get().contains(mRemoveViewReq.getViewUuid(i)))){
//						InboxDatabaseHelper.deleteView(mContext, mRemoveViewReq.getViewUuid(i)); //DB 작업
//					}
				}
			}else{ // 요청과 성공 갯수가 같으면 전부 날려버리자!
				for(int i = 0; i < removeViewRes.getRemoveSuccessUuidCount(); i++){
					// 성공적으로 지워진 뷰를 하나하나 확인하면서 Client 데이터베이스에도 날려버리자!
					InboxDatabaseHelper.deleteView(mContext, removeViewRes.getRemoveSuccessUuid(i)); //DB 작업
					// TODO : 채팅내용 지우기... 트리거 확인후 제거 및 추가 작업
//				ChatDatabaseHelper.deleteAllMessage(mContext);
				}
			}*/
			Log.e("test", "removeViewRes.getRemoveFailUuidCount() = " + removeViewRes.getRemoveFailUuidCount() + " / removeViewRes.getRemoveSuccessUuidCount() = " + 
					removeViewRes.getRemoveSuccessUuidCount());
			for(int i = 0; i < removeViewRes.getRemoveSuccessUuidCount(); i++)
				InboxDatabaseHelper.deleteView(mContext, removeViewRes.getRemoveSuccessUuid(i)); //DB 작업
			
			/*if(removeViewRes.getRemoveFailUuidCount() == 0)	//실패한 것이 없으므로 전부 날려버리자!!
			{
				InboxDatabaseHelper.deleteAllView(mContext);
			}
			else	//실패한 것이 있으므로 성공한 것만 날려버리자!!
			{
				for(int i = 0; i < removeViewRes.getRemoveSuccessUuidCount(); i++){
					// 성공적으로 지워진 뷰를 하나하나 확인하면서 Client 데이터베이스에도 날려버리자!
					InboxDatabaseHelper.deleteView(mContext, removeViewRes.getRemoveSuccessUuid(i)); //DB 작업
				}
			}*/
			
			Message msg = mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_REMOVE_VIEW_SUCCESS);
			msg.arg1 = removeViewRes.getRemoveFailUuidCount();
			mUiHandler.sendMessageAtFrontOfQueue(msg);
		} else{
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_REMOVE_VIEW_FAIL));
		}
	}
}
